import React from 'react';
import {
  Row,
  Col,
  Select,
  Button,
  Input,
  Form,
  DatePicker,
  Spin,
  Table,
  Pagination,
  message,
  Modal,
  Menu, 
  Dropdown,
  Icon
} from 'antd';
const { confirm } = Modal;
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  UserOutlined,
  CloseOutlined,
} from '@ant-design/icons';
// import { Page } from 'components'
import styles from './index.less';
import { connect } from 'dva';
import moment from 'moment';

import { PageHeaderWrapper } from '@ant-design/pro-layout';

const { Search } = Input;
const { RangePicker } = DatePicker;
const { Option } = Select;

@Form.create()
@connect(({ log }) => ({ log }))
class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currUserId: '',
      currSystemId: '',
      currLoginTime: '',
      currLoginOutTime: '',
      currType: '',
      timestamp: '',
      checkColumns: [
        { title: '日志编号', dataIndex: 'loginStaffId', key: 'loginStaffId' },
        { title: '系统模块', dataIndex: 'staffName', key: 'staffName' },
        { title: '操作类型', dataIndex: 'loginDate', key: 'loginDate' },
        { title: '请求方式', dataIndex: 'logoutDate', key: 'logoutDate' },
        { title: '操作人员', dataIndex: 'ip', key: 'ip' },
        { title: '主机', dataIndex: 'systemName', key: 'systemName' },
        { title: '操作地点', dataIndex: 'systemName', key: 'systemName' },
        { title: '操作状态', dataIndex: 'systemName', key: 'systemName' },
        { title: '操作日期', dataIndex: 'systemName', key: 'systemName' },
        {
          title: '动作',
          dataIndex: 'onlineStatusCd',
          key: 'onlineStatusCd',
          width: 200,
          render: (text, record) => (
            <a><Icon type="eye" style={{marginRight: '5px'}} />详细</a>
          ),
        },
      ],
      dataList: [],
      totalPage: 1,
      pageSize: 10,
      totalData: 3,
      currentPage: 1,
      loading: false,
      selectedRowKeys: [],
      value: undefined,

      systemNameList: [],

      timeVisible: false,
      logId: []
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.querySystemNameList()
  };

  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'log/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        if(res['list']){
          this.setState({
            systemNameList: res.list ? res.list : [],
          },()=>{
            this.querySever();
          });
        }else{
          message.error(res.msg)
        }
      });
  };

  //系统名称修改
  systemIdChange = value => {
    this.setState({
      currSystemId: value,
    });
    // const { systemNameList } = this.state;
    // for(let i=0;i<systemNameList.length;i++){
    //   if(value == systemNameList[i].systemId){
    //     this.setState({
    //       currSystemName: systemNameList[i].systemName
    //     })
    //   }
    // }
  };

  //获取用户列表
  querySever = async () => {
    this.setState({ loading: true });
    const { props } = this;
    const { currLoginTime, currLoginOutTime } = this.state;
    await props
      .dispatch({
        type: 'log/queryOptionList',
        payload: {
            dir: "asc",
            startDate: currLoginTime!=''?currLoginTime.split(' - ')[0]:'',
            endDate: currLoginTime!=''?currLoginTime.split(' - ')[1]:'',
            loginOutEndDate: currLoginOutTime!=''?currLoginOutTime.split(' - ')[1]:'',
            loginOutStartDate: currLoginOutTime!=''?currLoginOutTime.split(' - ')[0]:'',
            loginStaffId: this.state.currUserId,
            page: this.state.currentPage,
            rows: this.state.pageSize,
            systemId: this.state.currSystemId
        },
      })
      .then(res => {
        this.setState({
          loading: false,
          dataList: res.list ? res.list : [],
          totalData: res.total,
        });
        console.log(res, 'res');
      });
  };

  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  //用户名称修改
  userIdChange = e => {
    this.setState({
      currUserId: e.target.value,
    });
  };

  //登录/登出时间控件
  clearFun = (type) => {
    if(type=='login'){
      this.setState({
        currLoginTime: ''
      })
    }else{
      this.setState({
        currLoginOutTime: ''
      })
    }
  }

  setTimeFun = (type,time) => {
    if(type=='login'){
      if(time == 'today'){
        this.setState({currLoginTime: moment().format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'yesterday'){
        this.setState({currLoginTime: moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'sevenDays'){
        this.setState({currLoginTime: moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'thirtyDays'){
        this.setState({currLoginTime: moment().subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'halfAyear'){
        this.setState({currLoginTime: moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'currMonth'){
        this.setState({currLoginTime: moment().month(moment().month()).startOf('month').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().month(moment().month()).endOf('month').format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'lastMonth'){
        this.setState({currLoginTime: moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD HH:mm:ss')})
      }
    }else{
      if(time == 'today'){
        this.setState({currLoginOutTime: moment().format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'yesterday'){
        this.setState({currLoginOutTime: moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'sevenDays'){
        this.setState({currLoginOutTime: moment().subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'thirtyDays'){
        this.setState({currLoginOutTime: moment().subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'halfAyear'){
        this.setState({currLoginOutTime: moment().subtract(6, 'months').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'currMonth'){
        this.setState({currLoginOutTime: moment().month(moment().month()).startOf('month').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().month(moment().month()).endOf('month').format('YYYY-MM-DD HH:mm:ss')})
      }else if(time == 'lastMonth'){
        this.setState({currLoginOutTime: moment().month(moment().month() - 1).startOf('month').format('YYYY-MM-DD HH:mm:ss')+' - '+moment().month(moment().month() - 1).endOf('month').format('YYYY-MM-DD HH:mm:ss')})
      }
    }
  }

  //自定义时间
  customTimeFun = (type) => {
      this.props.form.resetFields();
      this.setState({
        timeVisible: true,
        currType: type
      })
  }

  timeHandleOk = () =>{
    const { validateFields, getFieldsValue } = this.props.form;
    let _this = this;
    validateFields(errors => {
      if (errors) {
        return;
      }
      const data = { ...getFieldsValue() };
      if(_this.state.currType == 'login'){
        _this.setState({
          currLoginTime: data.time[0].format('YYYY-MM-DD HH:mm:ss')+' - '+data.time[1].format('YYYY-MM-DD HH:mm:ss')
        })
      }else{
        _this.setState({
          currLoginOutTime: data.time[0].format('YYYY-MM-DD HH:mm:ss')+' - '+data.time[1].format('YYYY-MM-DD HH:mm:ss')
        })
      }
      _this.setState({
        timeVisible: false,
      })
    });
  }

  timeHandleCancel = () =>{
    this.setState({
      timeVisible: false
    })
  }

  //提交订单
  submitFun = () => {
    this.querySever();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currUserId: '',
        currSystemId: '',
        currLoginTime: '',
        currLoginOutTime: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.querySever();
      },
    );
  };

  //删除
  deleteFun = () => {
    let _this = this;
    confirm({
      title: '提示',
      content: '是否删除选中日志？',
      okText: '确认',
      cancelText: '取消',
      onOk:()=>{
        console.log(_this.state.logId,'======')
        _this.props
          .dispatch({
            type: 'log/deleteListPost',
            payload: _this.state.logId
          })
          .then(res => {
            if(res.code == 0){
              message.success('删除成功！')
              this.querySever();
            }else{
              message.error(res.msg)
            }
          });
      },
      onCancel:()=>{

      }
    })
  }

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.querySever();
      },
    );
  };

  onSelectChange = (selectedRowKeys,selectedRows) => {
    let logIds = []
    for(let i=0;i<selectedRows.length;i++){
      logIds.push(selectedRows[i].logId)
    }
    this.setState({
      logId: logIds
    })
    this.setState({ selectedRowKeys });
  };


  render() {
    const { checkColumns, systemNameList, dataList, timestamp, selectedRowKeys } = this.state;

    const { getFieldDecorator } = this.props.form;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <PageHeaderWrapper title={false} breadcrumb={false}>
      <div className={styles.mainPage}>
        <Row>
          <Col span={24}>
            <dl key={timestamp+1}>
              <dt>
                <Form name="horizontal_search" layout="inline">
                    <Form.Item name="username" label="系统模块">
                        <Input
                        style={{ width: 200 }}
                        type="text"
                        placeholder="请输入系统模块"
                        defaultValue={this.state.currUserId}
                        onChange={this.userIdChange}
                        />
                    </Form.Item>
                    <Form.Item name="systemId" label="操作人员">
                        <Select
                            allowClear
                            style={{ width: 200 }}
                            placeholder="请选择操作人员"
                            onChange={this.systemIdChange}
                            initialValue={this.state.currSystemId}
                        >
                            {
                            systemNameList.map(item=>{
                                return(<Option value={item.systemId}>{item.systemName}</Option>)
                            })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="systemId" label="类型">
                        <Select
                            allowClear
                            style={{ width: 200 }}
                            placeholder="请选择类型"
                            onChange={this.systemIdChange}
                            initialValue={this.state.currSystemId}
                        >
                            {
                            systemNameList.map(item=>{
                                return(<Option value={item.systemId}>{item.systemName}</Option>)
                            })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="systemId" label="状态">
                        <Select
                            allowClear
                            style={{ width: 200 }}
                            placeholder="请选择状态"
                            onChange={this.systemIdChange}
                            initialValue={this.state.currSystemId}
                        >
                            {
                            systemNameList.map(item=>{
                                return(<Option value={item.systemId}>{item.systemName}</Option>)
                            })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="systemId" label="操作时间">
                        <Select
                            allowClear
                            style={{ width: 200 }}
                            placeholder="请选择操作时间"
                            onChange={this.systemIdChange}
                            initialValue={this.state.currSystemId}
                        >
                            {
                            systemNameList.map(item=>{
                                return(<Option value={item.systemId}>{item.systemName}</Option>)
                            })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={this.submitFun}>
                            <SearchOutlined />
                            查询
                        </Button>
                        <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                            <SyncOutlined />
                            重置
                        </Button>
                    </Form.Item>
                </Form>
                <Form name="horizontal_search" layout="inline">
                    <Form.Item>
                        <Button type="primary" onClick={this.submitFun}>
                            <Icon type="close" />
                            删除
                        </Button>
                        <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                            <Icon type="delete" />
                            清空
                        </Button>
                        <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                            <Icon type="vertical-align-bottom" />
                            导出
                        </Button>
                    </Form.Item>
                </Form>
              </dt>
              <dd>
              <Modal
                  title="时间选择"
                  centered
                  visible={this.state.timeVisible}
                  okText="确定"
                  cancelText="取消"
                  onOk={this.timeHandleOk}
                  onCancel={this.timeHandleCancel}
                >
                    <Form name="horizontal" layout="inline">
                      <Form.Item label="选择时间段" name="time">
                        {getFieldDecorator('time', {
                          initialValue: '',
                          rules: [
                            {
                              required: true,
                              message: '请输入时间段',
                            },
                          ],
                        })(<RangePicker 
                          showTime={{
                            hideDisabledOptions: true,
                            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
                          }}
                        format="YYYY-MM-DD HH:mm:ss" />)}
                      </Form.Item>
                    </Form>
                </Modal>
                <Spin spinning={this.state.loading} delay={500}>
                  <Table
                    style={{ marginTop: '20px' }}
                    bordered
                    columns={checkColumns}
                    dataSource={dataList}
                    simple
                    // scroll={{ x: 1200 }}
                    pagination={false}
                    rowSelection={rowSelection}
                  />
                </Spin>
                <p style={{ textAlign: 'center', marginTop: '20px' }}>
                  <Pagination
                    current={this.state.currentPage}
                    pageSize={this.state.pageSize}
                    total={this.state.totalData}
                    onChange={this.pageChange}
                  />
                </p>
              </dd>
            </dl>
          </Col>
        </Row>
      </div>
      </PageHeaderWrapper>
    );
  }
}

export default Index;
